package com.mrd.gtimp.base.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.SysMsgTemplate;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author hejj
 */
@Service
public class SysMsgTemplateBiz extends BaseBiz<SysMsgTemplate> {


    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("sysMsgTemplateDao")
    public void setBaseRepository(BaseRepository<SysMsgTemplate, String> baseRepository) {
        super.baseRepository = baseRepository;
    }


    public void saveOrupdateSysMsgTemplate(SysMsgTemplate sysMsgTemplate) throws SaveException,
            QueryException {
        if (StringUtils.isNotEmpty(sysMsgTemplate.getId())) {
            SysMsgTemplate entity = null;
            entity = baseRepository.findEntityById(sysMsgTemplate.getId());
            if (null != entity) {
                entity.setUseState("1");
                baseRepository.saveOrupdate(entity);
            }
        } else if (null != sysMsgTemplate.getProcess().getProcessId()) {
            Filter filter = new Filter();
            filter.setGroupOp(FilterGroupOption.AND);
            SearchRule searchRule = new SearchRule("process.processId", SearchRuleOption.eq, sysMsgTemplate
                    .getProcess().getProcessId());
            filter.addRule(searchRule);
            searchRule = new SearchRule("useState", SearchRuleOption.eq, "0");
            filter.addRule(searchRule);
            searchRule = new SearchRule("company", SearchRuleOption.eq, sysMsgTemplate.getCompany());
            filter.addRule(searchRule);
            List<SysMsgTemplate> sysMsgTemplates = baseRepository.findEntityByFilter(0, 0, filter, null);
            if (!sysMsgTemplates.isEmpty()) {
                for (SysMsgTemplate entity : sysMsgTemplates) {
                    entity.setUseState("1");
                }
            }
            baseRepository.saveOrUpdateEntities(sysMsgTemplates);
        }

        sysMsgTemplate.setId(null);
        baseRepository.saveOrupdate(sysMsgTemplate);
    }

}
